<template>
  <div class="work-efficient">
    <continer class="work-report">
      <template slot="search">
        <quickSearch
          :advForm="quickSearchForm"
          @QuickSearch="headerQuery"
        >
          <template slot="slotCom">
            <el-select style="margin-right:4px" v-model="trend" @change="handleTrendChange">
              <el-option
                v-for="item in trendList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select v-if="trend !== 3" v-model="time" @change="handleTimeChange">
              <el-option
                v-for="item in trendOptionList[trend]"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-date-picker
              v-else
              v-model="time"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleDatePickerChange"
            >
            </el-date-picker>
          </template>
          <template slot="slotCom1">
            <el-select style="margin-right:4px" v-model="organization" @change="handleOrganizationChange">
              <el-option
                v-for="item in organizationList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select v-model="efficient" multiple collapse-tags @change="handleEfficientChange">
              <el-option
                v-for="item in efficientOptionList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
        </quickSearch>
      </template>
      <template slot="oprate">
        <el-button type="primary" size="mini" @click="refresh">刷新</el-button>
      </template>
      <template slot="content">
        <div class="data-report">数据报表</div>
        <div class="charts-container">
          <div style="width:160px;background-color:#FBFBFB"></div>
          <div id="workEfficient" class="charts"></div>
        </div>
        <div class="data-report">数据详情
          <el-tooltip popper-class="tooltip-class">
            <div slot="content">
              <div>创建工单数：座席新创建的工单数量</div>
              <div>处理工单数：座席处理过的工单数量</div>
              <div>处理工单次数：座席处理工单的总次数</div>
              <div>领取工单次数：座席主动领取的工单数量</div>
              <div>转派工单次数：座席将工单转派给其他座席的总次数</div>
              <div>回退工单次数：座席将工单回退到之前节点的总次数</div>
              <div>完成工单数：座席作为工单最终处理人完成的工单数量</div>
              <div>终止工单次数：座席将工单终止的总次数</div>
            </div>
            <i class="V7_iconfont V7_iconV7tubiao_bangzhu-42" style="color:#B3B9C7; font-size:12px"></i>
          </el-tooltip>
          <!-- 表头设置 -->
          <el-dropdown trigger="click" style="float:right;color:#a6a6ae;margin-right:5px;">
            <span class="el-dropdown-link">
              <i title="自定义表头" class="V7_iconfont V7_iconV7tubiao_zidingyi fz14" :class="isClick? 'icon-active': ''"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <searchCheckBox
                :data="realHeader"
                @check-change="handleCheckChange"
              ></searchCheckBox>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <instiutionTable
          ref="tableRef"
          :pages="workTablePages"
          :instiutionTableData="workTableData"
          :instiutionTableHeader="workTableHeader"
        >
        </instiutionTable>
      </template>
    </continer>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref, Prop, Watch } from 'vue-property-decorator'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import quickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import instiutionTable from '@/common/views/institutionTable/institutionTable.vue'
import searchCheckBox from '@/components/configCommon/operate-modules/SearchCheckbox/index.vue'
import { commonAction, deepClone } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import { getNowFormatDate, getCurrentWeekFirstDay, getDateGap, getCurrentMonthFirstDay, getLastWeekData, getLastDate, lastMonthLast, lastMonthFirst, getMonthBetween } from './utils'
import * as echarts from 'echarts'
const workSource = [
  {
    label: '用户移动端',
    value: 1
  },
  {
    label: '网页端',
    value: 2
  },
  {
    label: '接口创建',
    value: 3
  }
]
@Component({
  name: 'workEfficient',
  components: {
    continer,
    quickSearch,
    instiutionTable,
    searchCheckBox
  }
})
export default class WorkEfficient extends Vue {
  [x: string]: any

  private get efficientOptionList () {
    if (this.organization === 1) {
      return (CommonModule as any).publicCache.userList.map(item => {
        this.agentMap[item._id] = item.agentName
        item.label = item.agentName
        item.value = item._id
        return item
      })
    } else if (this.organization === 4) {
      return (CommonModule as any).publicCache.queueList.map(item => {
        this.agentMap[item._id] = item.name
        item.label = item.name
        item.value = item._id
        return item
      })
    } else {
      return this.serviceGroup.map(item => {
        this.agentMap[item.id] = item.name
        return item
      })
    }
  }

  private serviceGroup: any = []
  private isClick = false
  private createCount = 0
  private endCount = 0
  private finishCount = 0
  private trend: number = 0
  private time: any = 'nowWeek'
  private organization: number = 1
  private efficient: any[] = []
  private trendList: any[] = [
    {
      label: '周维度',
      value: 0
    },
    {
      label: '月维度',
      value: 1
    },
    {
      label: '年维度',
      value: 2
    },
    {
      label: '自定义时间',
      value: 3
    }
  ]

  private agentMap: any = {}

  private organizationList: any[] = [
    {
      label: '坐席',
      value: 1
    },
    {
      label: '技能租',
      value: 4
    },
    {
      label: '服务组',
      value: 5
    }
  ]

  private trendOptionList: any[] = [
    [{ label: '本周', value: 'nowWeek' }, { label: '上周', value: 'lastWeek' }, { label: '过去7天', value: 'lastSevenDay' }],
    [{ label: '本月', value: 'nowMonth' }, { label: '上月', value: 'lastMonth' }, { label: '过去30天', value: 'lastTthirtyDay' }],
    [{ label: '今年', value: 'nowYear' }, { label: '去年', value: 'lastYear' }]
  ]

  private quickSearchForm: any = {
    form: {
      dateRange: '',
      modelId: [],
      source: []
    },
    advSearchOptions: [
      { label: '时间维度', inputType: 'slotCom' },
      { label: '统计维度', inputType: 'slotCom1' },
      { label: '工单类型', inputType: 'ele-select', placeholder: '请选择工单类型', name: 'modelId', clearable: true, multiple: true, selectData: [], defaultProp: { label: 'modelName', value: 'id' } },
      { label: '工单来源', inputType: 'ele-select', placeholder: '请选择工单来源', name: 'source', clearable: true, multiple: true, selectData: workSource, defaultProp: { label: 'label', value: 'value' } }
    ]
  }

  private get seatName () {
    if (this.organization === 1) {
      return '坐席'
    } else if (this.organization === 4) {
      return '技能组'
    } else if (this.organization === 5) {
      return '服务组'
    } else {
      return '坐席名称'
    }
  }

  private workTableHeader: any[] = [
    { label: '坐席', prop: 'agentMap' },
    { label: '创建工单数', prop: 'createCount' },
    { label: '处理工单数', prop: 'dealWrCount' },
    { label: '处理工单次数', prop: 'dealCount' },
    { label: '领取工单次数', prop: 'claimCount' },
    { label: '转派工单次数', prop: 'assignCount' },
    { label: '回退工单次数', prop: 'backCount' },
    { label: '完成工单数', prop: 'finishCount' },
    { label: '终止工单数', prop: 'endCount' }
  ]

  private realHeader: any[] = [
    { label: '坐席', prop: 'agentMap' },
    { label: '创建工单数', prop: 'createCount' },
    { label: '处理工单数', prop: 'dealWrCount' },
    { label: '处理工单次数', prop: 'dealCount' },
    { label: '领取工单次数', prop: 'claimCount' },
    { label: '转派工单次数', prop: 'assignCount' },
    { label: '回退工单次数', prop: 'backCount' },
    { label: '完成工单数', prop: 'finishCount' },
    { label: '终止工单数', prop: 'endCount' }
  ]

  private workTableData: any[] = []

  private startAndEnd = {
    start: '',
    end: ''
  }

  private isxAxisMonth: boolean = false

  private workTablePages = { // 表格分页
    current: 1,
    pageSize: 10,
    total: 100
  }

  private originData: any[] = []

  private efficientOptions: any = {
    legend: {
      orient: 'vertical',
      left: '20px',
      top: 0,
      icon: 'roundRect',
      width: 600,
      height: 600,
      itemWidth: 12,
      itemHeight: 12,
      itemGap: 12,
      itemStyle: {
        opacity: 1
      },
      textStyle: {
        padding: [0, 0, 0, 5]
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const list: any[] = []
        let listItem: string = ''
        params.forEach(x => {
          list.push(
            `
              <i style="display: inline-block;width: 10px;height: 10px;background:${x.color};margin-right: 5px;border-radius: 50%;}"></i>
              <span style="display:inline-block;">${x.seriesName}：</span>
              <span style="display:inline-block;float:right">${x.value}</span>
            `
          )
        })
        listItem = list.join('<br/>')
        return `<div>
                  <p style="margin-bottom: 5px">${params[0].name}</p>
                  ${listItem}
                </div>`
      }
    },
    xAxis: {
      type: 'category',
      axisTick: { show: false },
      data: []
    },
    yAxis: [
      {
        type: 'value'
      }
    ],
    grid: {
      left: 200,
      top: 24,
      bottom: 24
    },
    series: [
      {
        name: '创建工单数',
        type: 'bar',
        barGap: 0,
        emphasis: {
          focus: 'series'
        },
        data: [],
        itemStyle: {
          normal: {
            color: '#69D279',
            lineStyle: {
              color: '#69D279'
            }
          }
        }
      },
      {
        name: '处理工单数',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        data: [],
        itemStyle: {
          normal: {
            color: '#3E7FEF',
            lineStyle: {
              color: '#3E7FEF'
            }
          }
        }
      },
      {
        name: '处理工单次数',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        data: [],
        itemStyle: {
          normal: {
            color: '#FFBF00',
            lineStyle: {
              color: '#FFBF00'
            }
          }
        }
      },
      {
        name: '领取工单次数',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        data: [],
        itemStyle: {
          normal: {
            color: '#F36D38',
            lineStyle: {
              color: '#F36D38'
            }
          }
        }
      },
      {
        name: '转派工单次数',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        data: [],
        itemStyle: {
          normal: {
            color: '#36C3FC',
            lineStyle: {
              color: '#36C3FC'
            }
          }
        }
      },
      {
        name: '回退工单次数',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        data: [],
        itemStyle: {
          normal: {
            color: '#7536FC',
            lineStyle: {
              color: '#7536FC'
            }
          }
        }
      },
      {
        name: '完成工单数',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        data: [],
        itemStyle: {
          normal: {
            color: '#FCDC36',
            lineStyle: {
              color: '#FCDC36'
            }
          }
        }
      },
      {
        name: '终止工单数',
        type: 'bar',
        emphasis: {
          focus: 'series'
        },
        data: [],
        itemStyle: {
          normal: {
            color: '#F36D38',
            lineStyle: {
              color: '#F36D38'
            }
          }
        }
      }
    ]
  }

  private handleTrendChange (val) {
    if (val === 0) {
      if (!['nowWeek', 'lastWeek', 'lastSevenDay'].includes(this.time)) {
        this.time = 'nowWeek'
      }
    } else if (val === 1) {
      if (!['nowMonth', 'lastMonth', 'lastTthirtyDay'].includes(this.time)) {
        this.time = 'nowMonth'
      }
    } else if (val === 2) {
      if (!['nowYear', 'lastYear'].includes(this.time)) {
        this.time = 'nowYear'
      }
    }
    if (val !== 3) {
      this.getTableList()
    }
  }

  private handleTimeChange (val) {
    if (val) {
      this.getTableList()
    }
  }

  private handleOrganizationChange (val) {
    if (val) {
      this.organization = val
      if (val === 1) {
        this.$set(this.workTableHeader, 0, { label: '坐席', prop: 'agentMap' })
        this.$set(this.realHeader, 0, { label: '坐席', prop: 'agentMap' })
      } else if (val === 4) {
        this.$set(this.workTableHeader, 0, { label: '技能组', prop: 'agentMap' })
        this.$set(this.realHeader, 0, { label: '技能组', prop: 'agentMap' })
      } else if (val === 5) {
        this.$set(this.workTableHeader, 0, { label: '服务组', prop: 'agentMap' })
        this.$set(this.realHeader, 0, { label: '服务组', prop: 'agentMap' })
      }
      this.efficient = []
      this.getTableList()
    }
  }

  private handleEfficientChange (val) {
    if (this.originData) {
      this.workTableData = this.originData.map(item => {
        item.agentMap = this.agentMap[item.agentId || item.skId || item.seId]
        return item
      }).filter((item: { skId: any; seId: any; agentId: any, agentMap: any }) => {
        if (item.agentMap) {
          if (this.efficient.length === 0) {
            return item
          } else {
            if (this.organization === 1) {
              return this.efficient.includes(item.agentId)
            } else if (this.organization === 4) {
              return this.efficient.includes(item.skId)
            } else if (this.organization === 5) {
              return this.efficient.includes(item.seId)
            }
          }
        }
      })
      // // 更新图表
      this.getxAxisData(this.workTableData)
      this.getSeriesData(this.workTableData)
      this.drawCharts('#workEfficient', this.efficientOptions)
    }
  }

  private handleDatePickerChange (val) {
    if (val) {
      this.getTableList()
    }
  }

  private handleCheckChange (val) {
    this.workTableHeader = val.filter(item => item.show)
  }

  private getStartAndEnd () {
    const nowFormat = getNowFormatDate()
    if (this.time === 'nowWeek') {
      this.startAndEnd.start = getCurrentWeekFirstDay()
      this.startAndEnd.end = nowFormat
    } else if (this.time === 'lastWeek') {
      this.startAndEnd.start = getLastWeekData().startDay
      this.startAndEnd.end = getLastWeekData().endDay
    } else if (this.time === 'lastSevenDay') {
      this.startAndEnd.start = getLastDate(7)
      this.startAndEnd.end = nowFormat
    } else if (this.time === 'nowMonth') {
      this.startAndEnd.start = getCurrentMonthFirstDay()
      this.startAndEnd.end = nowFormat
    } else if (this.time === 'lastMonth') {
      this.startAndEnd.start = lastMonthFirst()
      this.startAndEnd.end = lastMonthLast()
    } else if (this.time === 'lastTthirtyDay') {
      this.startAndEnd.start = getLastDate(30)
      this.startAndEnd.end = nowFormat
    } else if (this.time === 'nowYear') {
      this.startAndEnd.start = new Date().getFullYear() + '-01-01'
      this.startAndEnd.end = nowFormat
    } else if (this.time === 'lastYear') {
      this.startAndEnd.start = new Date().getFullYear() - 1 + '-01-01'
      this.startAndEnd.end = new Date().getFullYear() - 1 + '-12-31'
    } else {
      this.startAndEnd.start = this.time[0]
      this.startAndEnd.end = this.time[1]
    }
  }

  private getTableList () { // 获取表格数据
    const { modelId, source, dateRange } = this.quickSearchForm.form
    this.getStartAndEnd()
    let start = this.startAndEnd.start + ' 00:00:00'
    let end = this.startAndEnd.end + ' 23:59:59'
    if (Array.isArray(dateRange) && dateRange.length === 2) {
      start = dateRange[0]
      end = dateRange[1]
    }
    const sedData: any = {
      agentId: [],
      skId: [],
      seId: [],
      start,
      end,
      modelId,
      source,
      dimensionType: this.organization
    }
    if (this.organization === 1) {
      sedData.agentId = this.efficient
    } else if (this.organization === 4) {
      sedData.skId = this.efficient
    } else if (this.organization === 5) {
      sedData.seId = this.efficient
    }
    commonAction({
      url: '/server-work/action/report/workOrderAgentReport',
      method: 'post',
      data: sedData
    }).then(res => {
      if (res.success) {
        if (res.data) {
          this.originData = deepClone(res.data)
          // this.workTableData = res.data
          this.workTableData = res.data.map(item => {
            item.agentMap = this.agentMap[item.agentId || item.skId || item.seId]
            return item
          }).filter((item: { skId: any; seId: any; agentId: any; agentMap: any }) => {
            if (item.agentMap) {
              if (this.efficient.length === 0) {
                return item
              } else {
                if (this.organization === 1) {
                  return this.efficient.includes(item.agentId)
                } else if (this.organization === 4) {
                  return this.efficient.includes(item.skId)
                } else if (this.organization === 5) {
                  return this.efficient.includes(item.seId)
                }
              }
            }
          })
          // // 更新图表
          this.getxAxisData(this.workTableData)
          this.getSeriesData(this.workTableData)
          this.drawCharts('#workEfficient', this.efficientOptions)
        }
      }
    })
  }

  private getWorkTypeList () {
    commonAction({
      url: '/server-work/action/workOrderModel/getCategory/filter',
      method: 'post',
      data: { filterPermission: 1 }
    }).then(res => {
      if (res.success) {
        const obj = this.quickSearchForm.advSearchOptions.find(item => item.label === '工单类型')
        if (obj) {
          obj.selectData = res.data
        }
      }
    })
  }

  private headerQuery () {
    this.getTableList()
  }

  private refresh () {
    this.getTableList()
  }

  private drawCharts (dom, option, setting = {}) {
    const node = document.querySelector(dom)
    let myChart = echarts.getInstanceByDom(node)
    if (!myChart) {
      myChart = echarts.init(node, '', setting)
    }
    myChart.setOption(option)
  }

  private getxAxisData (data) {
    let str = ''
    if (this.organization === 1) {
      str = 'agentId'
    } else if (this.organization === 4) {
      str = 'skId'
    } else if (this.organization === 5) {
      str = 'seId'
    }
    const xArray = data.map(item => this.agentMap[item[str]]).filter(item => item !== undefined)
    this.efficientOptions.xAxis.data = [...xArray]
  }

  private getSeriesData (data) {
    const length = this.efficientOptions.xAxis.data.length
    this.efficientOptions.series.forEach(item => {
      item.data = new Array(length).fill(0)
    })
    data.forEach((item, index) => {
      this.efficientOptions.series[0].data[index] = item.createCount
      this.efficientOptions.series[1].data[index] = item.dealWrCount
      this.efficientOptions.series[2].data[index] = item.dealCount
      this.efficientOptions.series[3].data[index] = item.claimCount
      this.efficientOptions.series[4].data[index] = item.assignCount
      this.efficientOptions.series[5].data[index] = item.backCount
      this.efficientOptions.series[6].data[index] = item.finishCount
      this.efficientOptions.series[7].data[index] = item.endCount
    })
  }

  private getServiceGroup () {
    commonAction({
      url: '/server-work/action/serviceGroup/list',
      method: 'post',
      data: { limit: 99, page: 1, name: '' }
    }).then(res => {
      if (res.success) {
        this.serviceGroup = res.data.list.map(item => {
          item.label = item.name
          item.value = item.id
          return item
        })
      }
    })
  }

  private mounted () {
    this.getServiceGroup()
    this.getWorkTypeList()
    this.getTableList()
    this.drawCharts('#workEfficient', this.efficientOptions)
  }
}
</script>

<style lang="stylus" scoped>
.work-efficient
  font-family: 'PingFang SC';
  font-style: normal;
  height: 100%
  .work-report
    /deep/.pages
      display: none
    /deep/.instiutionTable
      .tableBox
        padding-top 0
      // height: calc(100% - 340px)
    .data-report
      font-weight: 500;
      font-size: 14px;
      margin: 16px 0
    .charts-container
      display flex
      height: 350px
      border 1px solid #ECF0F3
      border-radius: 4px
      .charts
        height: 300px
        width: 100%
        margin auto 0 auto -160px
</style>
